import { markRaw, reactive } from 'vue';
import { defineStore, type StoreGeneric } from 'pinia';
import type { LoginParams } from '@/api/model/userModel';
import { setAuthCache } from '@/utils/auth';
import { tagsStore } from './tagsStore';
import { routes } from '@/router/routes';
import type { _RouteRecordBase } from 'vue-router';
import { filterAsyncRouter } from '@/utils/permission';
interface TokenObj {
  department: string;
  name: string;
  password: string;
  permissions: string;
  username: string;
}
interface State {
  token: string;
  user: Partial<TokenObj>;
  routes: _RouteRecordBase[];
}
const TOKEN_KEY = 'TOKEN_KEY';
export const useUserStore = defineStore('user', () => {
  const state: State = reactive({ token: '', user: {}, routes: [] });

  function setToken(info: string | undefined) {
    state.token = info ?? '';
    setAuthCache(TOKEN_KEY, info);
  }
  function login(params: LoginParams) {
    const token = '123';
    setToken(token);
    return new Promise((resolve) => {
      resolve(0);
    });
  }
  // 将访问过的路由固定到visited views bar
  function handleFixedVisitedViews(tagsViewStore: StoreGeneric, routes: _RouteRecordBase[]) {
    routes.forEach((route) => {
      if (route.meta && route.meta.fixed) {
        tagsViewStore.handleAddFixedVisitedView(route);
      }
      if (route.children && route.children.length)
        handleFixedVisitedViews(tagsViewStore, route.children);
    });
  }

  function setUser(token: any) {
    let routers = markRaw(routes());
    state.user = token;
    const accessedRouters = filterAsyncRouter(routers, state.user.permissions!);
    state.routes = accessedRouters;
    handleFixedVisitedViews(tagsStore(), routers);
  }

  return { login, setUser, state };
});
